package com.newlink.building.record.fragment

import android.content.Intent
import android.os.Looper
import android.view.View
import com.chad.library.adapter.base.BaseQuickAdapter
import com.newlink.building.common_base.activities.Base_ImageZoomActivityNL
import com.newlink.building.common_base.base.BaseMvpFragment
import com.newlink.building.common_base.event.AlarmNotifyBean
import com.newlink.building.common_base.event.MessageEvent
import com.newlink.building.common_base.event.TYPE_APP_MQTT_NOTIFY_ALARM
import com.newlink.building.common_base.ext.setNewOrAddData
import com.newlink.building.common_base.model.bean.SecurityRecordListData
import com.newlink.building.common_base.utils.NLog
import com.newlink.building.common_base.utils.WeakHandler
import com.newlink.building.record.R
import com.newlink.building.record.adapter.Module_Record_SecurityRecordAdapter
import com.newlink.building.record.databinding.FragmentSecurityRecordBinding
import com.newlink.building.record.mvp.Module_Record_SecurityRecordPresenter
import com.newlink.building.record.mvp.contract.Module_Record_SecurityRecordContract
import org.greenrobot.eventbus.EventBus

/**
 * @author wangyang
 * @date 2022/9/29
 * @description 记录——安防记录页面
 */
class Module_Record_SecurityRecordFragment :
    BaseMvpFragment<Module_Record_SecurityRecordContract.View, Module_Record_SecurityRecordContract.Presenter>(),
    Module_Record_SecurityRecordContract.View {

    private val weakHandler by lazy { WeakHandler(Looper.getMainLooper()) }
    private var curList: MutableList<SecurityRecordListData> = ArrayList()

    //当前页数
    var curPage: Int = 1

    //每页加载数量
    var curLimit: Int = 20
    var mAdapter: Module_Record_SecurityRecordAdapter? = null
    var isRefreshLayoutRequest: Boolean = false
    private var empty_content: View? = null

//    override fun attachLayoutRes(): Int {
//        return R.layout.fragment_security_record
//    }

    private lateinit var mBinding: FragmentSecurityRecordBinding
    override fun attachLayoutRes(): View {
        mBinding = FragmentSecurityRecordBinding.inflate(layoutInflater)
        return mBinding.root
    }

    override fun initView(view: View) {
        empty_content = view.findViewById(R.id.empty_content)
        mBinding.swipeRefreshLayout.setOnRefreshListener {
            isRefreshLayoutRequest = true

            weakHandler.postDelayed({
                curPage = 1
                lazyLoad()
            }, 500)
        }
        mAdapter = Module_Record_SecurityRecordAdapter(curList)
        mAdapter?.setAnimationWithDefault(BaseQuickAdapter.AnimationType.AlphaIn)
        mAdapter?.setOnItemChildClickListener { adapter, view, position ->
            if (view.id == R.id.iv_preview) {
                val securityRecordListData = curList[position]
                Intent(activity, Base_ImageZoomActivityNL::class.java).apply {
                    putExtra("image_url", securityRecordListData.fileUrl)
                    startActivity(this)
                }
            }
        }
        mBinding.rvSecurityRecord.adapter = mAdapter
        mAdapter?.setOnItemClickListener { _, _, position ->
            val securityRecordListData = curList[position]

//            data class Data(
//                val id: Long,
//                val mac: String,
//                val devName: String,
//                val sip: String,
//                val alarmType:Int ,
//                val alarmDesc:String ,
//                val alarmTime: String,
//                val handle: Int,
//                val alarmIndex: Int,
//            )

            val data = AlarmNotifyBean.Data(
                securityRecordListData.id,
                securityRecordListData.mac,
                securityRecordListData.devName,
                securityRecordListData.sip,
                securityRecordListData.alarmType,
                securityRecordListData.alarmDesc,
                securityRecordListData.alarmTime,
                securityRecordListData.handle,
                securityRecordListData.alarmIndex
            )

            NLog.e("[jake] => <${javaClass.simpleName}>   click alarmBean is $data")
//            GlobalPopoverActivity.startSelf(activity, data, fromRecord = true)
            EventBus.getDefault()
                .post(
                    MessageEvent(
                        TYPE_APP_MQTT_NOTIFY_ALARM,
                        AlarmNotifyBean(data = data, fromRecord = true)
                    )
                )
        }

        mAdapter?.run {
            loadMoreModule.isAutoLoadMore = true
            loadMoreModule.isEnableLoadMoreIfNotFullPage = false
            loadMoreModule.setOnLoadMoreListener {
                isRefreshLayoutRequest = false
                ++curPage
                showLoading()
                weakHandler.postDelayed({ lazyLoad() }, 500)
            }
        }
    }

    override fun lazyLoadDataIfPrepared() {
    }

    override fun lazyLoad() {
        NLog.e("[jake]..  SecurityRecordFragment lazyLoad .. 加载安防数据")
        mPresenter?.getSecurityRecordList(accessToken, curPage, curLimit)
    }

    override fun onResume() {
        super.onResume()
        curPage = 1
        lazyLoad()
    }

    override fun showLoading() {
        mBinding.swipeRefreshLayout.isRefreshing = true
    }


    override fun hideLoading() {
        isRefreshLayoutRequest = false
        mBinding.swipeRefreshLayout.isRefreshing = false
    }

    override fun createPresenter(): Module_Record_SecurityRecordContract.Presenter = Module_Record_SecurityRecordPresenter()

    override fun getSecurityRecordListSuccess(
        total: Int,
        list: MutableList<SecurityRecordListData>?
    ) {

        if (isRefreshLayoutRequest) {
//            showToast(getString(R.string.default_list_data_refresh))
            hideLoading()
            curList?.clear()
        }

        list?.let {
            if (curPage == 1) {//加载第一页
                NLog.e("is first page,set new data")
                curList.clear()
                curList = it
                mAdapter?.setNewOrAddData(true, list)
            } else {//不是第一页,则添加数据
                NLog.e("current page is $curPage,add data")
                curList.addAll(it)
                mAdapter?.setNewOrAddData(false, list)
            }
        }
        NLog.e("display size:${curList.size} total:$total pageNum:$curPage ")
        //小于总条数,继续加载更多,否则停止加载更多
        if (curList.size < total) {
            mAdapter?.loadMoreModule?.loadMoreComplete()
        } else {
            mAdapter?.loadMoreModule?.loadMoreEnd()
        }

        //是否加载空页面
        if (curList == null || curList?.size == 0) {
            empty_content?.visibility = View.VISIBLE
            mBinding.rvSecurityRecord.visibility = View.GONE
        } else {
            empty_content?.visibility = View.GONE
            mBinding.rvSecurityRecord.visibility = View.VISIBLE
        }
    }

    override fun getSecurityRecordListFail() {
        hideLoading()
    }
}